//
//  MYHTTPModel.swift
//  swift2.0项目开始
//
//  Created by 龚昕炜 on 16/7/30.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

class MYHTTPModel: NSObject {
    /**
    access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
    uid	false	int64	需要查询的用户ID。
    screen_name	false	string	需要查询的用户昵称。
    */
    var access_token: String?
    var uid: String?
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expires_date: NSDate?
    
    /** 昵称 */
    var screen_name: String?
    /** 头像 */
    var profile_image_url: String?
    
    var name: String?
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        self.setValuesForKeysWithDictionary(dict)
    }
    
    /** 加上static修饰符是为了让类方法中可以访问 */
    static let userInfoPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("user.archive")
    
    class func readModel() -> MYHTTPModel? {
        
        let model = NSKeyedUnarchiver.unarchiveObjectWithFile(MYHTTPModel.userInfoPath) as? MYHTTPModel
//        print(MYHTTPModel.userInfoPath)
        /**
            1.在这里判断token的时效
            2.如果没有过期就返回token
            3.过期了返回nil
         */
        
        guard let date = model?.expires_date else {
            return nil
        }
        
        if date.compare(NSDate()) == .OrderedAscending {
            return nil
        } else if date.compare(NSDate()) == .OrderedSame {
            return nil
        } else {
            return model
        }
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    /** 归档 */
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /// 解档 - 将二进制数据从磁盘读取并且转换成对象时被调用，与网络的反序列化类似
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}

/** 归档 */
extension MYHTTPModel: NSCoding {
    
    func saveUserInfo() {
        /** 路径 */
//        let path = MYHTTPModel.userInfoPath
        
        /** 归档保存 */
        NSKeyedArchiver.archiveRootObject(self, toFile: MYHTTPModel.userInfoPath)
        print(MYHTTPModel.userInfoPath)
    }
    
}
